// import { queryProjectDetail } from '../../services/project'
import { queryProjectInstDetail, queryOrderInfoDetail, uploadImg } from '../../services/order'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId:"",
    projectId:"",
    instId:"",
    orderInfo:{},
    defaultPictureUrl:'../../assets/inspect/photo.png',
    inspectList:[],
    token: "",
    moduleData: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    // console.log("options>>>", options)
    let orderId = options.orderId
    let projectId = options.projectId
    let instId = options.instId
    this.setData({
      orderId,
      projectId,
      instId
    })
    console.log("orderId>>>",orderId)
    console.log("projectId>>>",projectId)
    this.getProjectInstDetail(instId)
    this.getOrderInfoDetail(orderId)
    this.setData({
      token: wx.getStorageSync('token')
    })
  },

  onShow(){
    this.setData({
      token: wx.getStorageSync('token')
    })
  },

  async getOrderInfoDetail(orderId){
    let orderRes = await queryOrderInfoDetail(orderId)
    if(orderRes.code === 200){
      this.setData({
        orderInfo: orderRes.data
      })
    }
  },

  async getProjectInstDetail(instId){
    if(!this.checkIfExist(instId)){
      let proRes = await queryProjectInstDetail(instId)
      if(proRes.code === 200){
        let proInfo = proRes.data
        if(proInfo.itemJson){
          this.setData({
            inspectList: JSON.parse(proInfo.itemJson)
          })
        }
      }

    }
  },

  checkIfExist(instId){
    const tempStorageOrder = wx.getStorageSync('tempStorageOrder')
    let res = false
    if(tempStorageOrder){
      const index = tempStorageOrder.findIndex(item => item.id == instId)
      if(index > -1){
        let currentItem = tempStorageOrder[index]
        let jsonList = JSON.parse(currentItem.itemJson)
        this.dealJson(jsonList)
        this.setData({
          inspectList: jsonList
        })
        res = true
      }
    }
    return res
  },

  handlePhotoShoot(event){
    const field = event.currentTarget.dataset.field
    const currentItem = event.currentTarget.dataset.item

    // currentItem[field] = 'https://img95.699pic.com/photo/40041/1120.jpg_wh860.jpg'
    // this.changePic(currentItem)
    const _this = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const fs = wx.getFileSystemManager()
        fs.readFile({
          filePath: res.tempFiles[0].tempFilePath,
          encoding: 'base64',
          success(readRes){
            uploadImg(readRes.data).then(picRes => {
              if(picRes.code === 200){
                currentItem[field] = picRes.msg
                _this.changePic(currentItem)
              }
            })
          } 
        })
      }
    })
  },

  changePic(newItem){
    const newIndex = this.data.inspectList.findIndex(item => item.id === newItem.id)
    this.setData({
      [`inspectList[${newIndex}]`]: newItem
    })
    this.dealJson(this.data.inspectList)
  },

  dealJson(jsonList){
    let dataMap = {}
    jsonList.forEach(item => {
      if(item.isCollection == 'yes'){
        if(!dataMap[item.moduleName]){
          dataMap[item.moduleName] = []
          dataMap[item.moduleName].push(item)
        }else {
          dataMap[item.moduleName].push(item)
        }
      }
    })
    let moduleData = []
    for(let key in dataMap){
      moduleData.push({
        moduleName: key,
        moduleList: dataMap[key]
      })
    }
    if(moduleData.length){
      this.setData({
        moduleData
      })
    }
  },

  onChangeRes(val){
    const currentItem = val.currentTarget.dataset.currentitem
    const newIndex = this.data.inspectList.findIndex(item => item.id === currentItem.id)
    currentItem.checkRes = val.detail
    this.setData({
      [`inspectList[${newIndex}]`]: currentItem
    })
  },

  confirmInfo(){
    // const checkInspectList = this.data.inspectList
    // const noPassData = checkInspectList.find(item => !item.checkRes)
    // if(noPassData){
    //   Toast.fail(`${noPassData.label+':'+noPassData.name}的检查结果为空,请检查!`);
    //   return
    // }
    let channelInfo = {
      id: this.data.instId,
      itemJson: JSON.stringify(this.data.inspectList)
    }

    wx.navigateBack()
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit("instItemChange", channelInfo)
  }


})